import type { ActionType, ProColumns, ProFormInstance } from '@ant-design/pro-components';
import { ProFormSelect, ProTable } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Modal, Select, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { deleteRoomsDelete, getRoomList, putRoomsEditRoomName } from './request';
import { DeleteOutlined, ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import {
  getBuildingsList,
  getBuildingsView,
  getRoomTypeList,
  getRoomTypeView,
} from '../BuildingType/request';
import IdentityProvider from './components/IdentityProvider';
import AddOneRoom from './components/AddOneRoom';
import { useDeleteConfirm } from '@/hooks/useAlartMolder';
import { useIntl } from '@umijs/max';

export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

// 定义表格数据源类型
export type GithubIssueItem = {
  id: number;
  roomId: string;
  roomName: string;
  roomType: number;
  floor: string;
  mainRoomId: string;
  isSuite: number;
  subRoomCount: number;
  lockType: number;
  status: number;
  b_name: string;
  t_name: string;
  buildingId?: any;
  roomNo?: any;
  roomTypeId?: number;
};

const Index: React.FC = () => {
  // 显示表格或者批量添加房间
  const [show, setShow] = useState(false);

  // 新增/修改对话框显示状态
  const [modalShow, setModalShow] = useState(false);

  // 表格操作源
  const actionRef = useRef<ActionType>();

  // 修改的行keys
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // 楼层可选择数据
  const [floorList, setFloorList] = useState([]);

  // 选择表格数据
  const [selectList, setSelectList] = useState<React.Key[]>([]);

  // 表格搜索操作源
  const ref = useRef<ProFormInstance>();

  const intl = useIntl()

  // 表格左侧选择变化时触发
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectList(newSelectedRowKeys);
  };

  // 楼栋变化时触发---楼层根据楼栋对应获取
  const buildingChange = async (e: number) => {
    ref.current?.setFieldsValue({ floor: '' });
    const res = await getBuildingsView(e);
    if (e && res.data.floor) {
      const list = res.data.floor || [];
      setFloorList(
        list.split(',').map((v: any) => {
          return {
            label: v,
            value: v.slice(0, -1),
            key: v,
          };
        }),
      );
    } else {
      setFloorList([]);
    }
  };

  // 获取房型
  const [roomTypeList, setRoomTypeList] = useState([]);
  const getType = async () => {
    const res = await getRoomTypeList();
    if (res.data.list) {
      const list = res.data.list.map((v: any) => {
        return { label: v.name, value: v.id };
      });
      setRoomTypeList(list);
      return;
    }
    setRoomTypeList([]);
  };

  useEffect(() => {
    getType();
  }, []);

  // 操作的信息
  const [info, setInfo] = useState<GithubIssueItem | null>(null);
  const [id, setId] = useState<number>(0);

  // 打开新增/修改对话框
  const open = (record?: GithubIssueItem) => {
    if (record) {
      setId(record.id);
      setInfo(record);
    }
    setModalShow(true);
  };

  // 确认删除触发
  const confirmDel = async (record: GithubIssueItem) => {
    const res: any = await deleteRoomsDelete(String(record.id));
    if (res.code !== 0) {
      message.error(res.msg);
      return;
    }
    message.success(intl.formatMessage({ id: "RoomSettings.Room deleted" }));
    actionRef.current?.reload();
  };

  const { confirm } = Modal;

  // 批量删除方法
  const batch = async () => {
    const res: any = await deleteRoomsDelete(selectList.join(','));
    if (res.code !== 0) {
      message.error(res.msg);
      return;
    }
    message.success(intl.formatMessage({ id: "RoomSettings.Room deleted" }));
    actionRef.current?.reload();
  };

  // 是否确认批量删除
  const batchDelete = () => {
    if (selectList.length) {
      confirm({
        title: intl.formatMessage({ id: "RoomSettings.delected room" }),
        icon: <ExclamationCircleFilled />,
        onOk() {
          batch();
        },
        onCancel() { },
      });
    }
  };

  // 表格列配置
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: intl.formatMessage({ id: 'FixLock.serial' }),
      dataIndex: 'inedx',
      valueType: 'index',
      width: 60,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: 'FixLock.Building Name' }),
      dataIndex: 'b_name',
      ellipsis: false,
      editable: false,
      renderFormItem: () => {
        return (
          <ProFormSelect
            width={'md'}
            name="b_id"
            request={async () => {
              const res = await getBuildingsList({});
              const list = res.data.list || [];
              return list.map((v: any) => {
                return { label: `${v.bno}${intl.formatMessage({ id: "FixLock.building" })}`, value: v.id };
              });
            }}
            placeholder={intl.formatMessage({ id: "RoomSettings.Please select the building" })}
            onChange={buildingChange}
          />
        );
      },
    },
    {
      title: intl.formatMessage({ id: "FixLock.Floor" }),
      dataIndex: 'floor',
      ellipsis: false,
      editable: false,
      key: 'floor',
      renderFormItem: () => {
        return <Select style={{ width: '100%' }} placeholder={intl.formatMessage({ id: "RoomSettings.Select Floor" })} options={floorList} />;
      },
    },
    {
      title: intl.formatMessage({ id: 'FixLock.Room Type' }),
      dataIndex: 't_name',
      key: 't_name',
      ellipsis: false,
      valueType: 'select',
      tooltip: intl.formatMessage({ id: "RoomSettings.Modifiable room type" }),
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormSelect
            width={'md'}
            name="room_type_id"
            options={roomTypeList}
            placeholder={intl.formatMessage({ id: "RoomSettings.Please select the room type" })}
          />
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'FixLock.Room Type' }),
      dataIndex: 't_name',
      key: 't_name',
      ellipsis: false,
      valueType: 'select',
      tooltip: intl.formatMessage({ id: "RoomSettings.Modifiable room type" }),
      search: false,
      renderFormItem: () => {
        return <Select style={{ width: '100%' }} options={roomTypeList} placeholder={intl.formatMessage({ id: "RoomSettings.Please select the room type" })} />;
      },
      render: (_, record) => (
        <Space>
          <a style={{ color: record.t_name === '双人床' ? 'skyblue' : '' }}>{record.t_name}</a>
        </Space>
      ),
    },
    {
      title: intl.formatMessage({ id: "RoomSettings.room" }) + ' ID',
      dataIndex: 'roomId',
      ellipsis: false,
      search: false,
      editable: false,
      tooltip: intl.formatMessage({ id: "RoomSettings.The room ID consists" }),
    },
    {
      title: intl.formatMessage({ id: "FixLock.Room number" }),
      dataIndex: 'roomNo',
      ellipsis: false,
      search: false,
      editable: false,
    },
    {
      title: intl.formatMessage({ id: "RoomSettings.Room name" }),
      dataIndex: 'roomName',
      ellipsis: false,
      tooltip: intl.formatMessage({id:'RoomSettings.The name of the room'}),
      key: 'roomName',
    },
    {
      title: intl.formatMessage({id:"RoomSettings.Is suite"}),
      dataIndex: 'isSuite',
      ellipsis: false,
      search: false,
      editable: false,
      renderText(text) {
        if (text === 0) {
          return intl.formatMessage({id:"RoomSettings.No"});
        } else if (text === 1) {
          return intl.formatMessage({id:"RoomSettings.Yes"});
        }
        return intl.formatMessage({id:"RoomSettings.Unknown"});
      },
    },
    {
      title: intl.formatMessage({id:'RoomSettings.Main room'}) +' ID',
      dataIndex: 'mainRoomId',
      ellipsis: false,
      search: false,
      editable: false,
    },
    {
      title: intl.formatMessage({id:"RoomSettings.Number of bedrooms"}),
      dataIndex: 'subRoomCount',
      ellipsis: false,
      search: false,
      editable: false,
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   ellipsis: true,
    //   search: false,
    //   editable: false,
    //   renderText(text) {
    //     if (text === 0) {
    //       return '干净房';
    //     } else if (text === 1) {
    //       return '脏房';
    //     } else if (text === 2) {
    //       return '入住房';
    //     } else if (text === 3) {
    //       return '维修房';
    //     }
    //     return '未知';
    //   },
    // },
    {
      title: intl.formatMessage({id:'RoomSettings.Lock type'}),
      dataIndex: 'lock_type',
      ellipsis: false,
      search: false,
      editable: false,
      renderText(text) {
        if (text === 1) {
          return intl.formatMessage({id:"RoomSettings.Single"});
        } else if (text === 2) {
          return '2.4G';
        } else if (text === 3) {
          return 'BLE';
        }
        return intl.formatMessage({id:"RoomSettings.Unknown"});
      },
    },
    {
      title: intl.formatMessage({id:'FixLock.Action'}),
      align: 'center',
      valueType: 'option',
      key: 'option',
      search: false,
      width: 160,
      render: (_text: any, record: GithubIssueItem) => (
        <>
          <Button
            key="editable"
            type="link"
            onClick={() => {
              actionRef.current?.startEditable(record.id);
              return;
            }}
          >
            {/* 修改 */}
            {intl.formatMessage({id:'FixLock.modify'})}
          </Button>
          <a onClick={() => {
            useDeleteConfirm(`${intl.formatMessage({id:"RoomSettings.Do you want to delete it"})}  ${record.roomName}`, "", (val) => {
              if (val) {
                confirmDel(record)
              }
            })
          }} style={{ color: "red" }}>
              {intl.formatMessage({id:'FixLock.delete'})}
          </a>
        </>
      ),
    },
  ];
  return (
    <>
      {!show && (
        <>
          <ProTable<GithubIssueItem>
            rowKey="id"
            defaultSize={'large'}
            columns={columns}
            actionRef={actionRef}
            cardBordered={false}
            formRef={ref}
            rowSelection={{
              type: 'checkbox',
              onChange: onSelectChange,
            }}
            request={async (params) => {
              await waitTime(500);
              const res: any = await getRoomList({
                ...params,
                page: params.current,
              });
              console.log(params);
              console.log(res.data.list);
              return {
                data: res.data.list || [],
                success: res.code === 0 ? true : false,
                total: res.data.totalCount,
              };
            }}

            

            editable={{
              type: 'multiple',
              editableKeys,
              actionRender: (row, config, dom) => [dom.save, dom.cancel],
              onChange: (e) => {
                setEditableRowKeys(e);
              },
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              onSave: async (rowKey, data, row) => {
                const {
                  data: { name },
                } = await getRoomTypeView(Number(data.t_name));


                const res: any = await putRoomsEditRoomName({
                  id: data.id,
                  roomName: data.roomName,
                  room_type_id: name ? data.t_name : data.roomTypeId,
                });
                if (res.code !== 0) return message.error(res.msg);
                message.success(res.msg);
                actionRef.current?.reload();

                return;
              },
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              onCancel: async (rowKey, data, row) => {
              },
            }}
            search={{ labelWidth: 'auto' }}
            options={{
              setting: {
                listsHeight: 400,
              },
            }}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
            }}
            dateFormatter="string"
            toolBarRender={() => [
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  setShow(true);
                }}
                type="primary"
              >
                {/* 批量新增 */}
                {intl.formatMessage({id:"RoomSettings.Add in batches"})}
              </Button>,
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  open();
                }}
                type="primary"
              >
              {intl.formatMessage({id:"RoomSettings.Newly built"})}
              </Button>,
              <Button
                key="dashed"
                icon={<DeleteOutlined />}
                onClick={batchDelete}
                type="primary"
                danger
                disabled={selectList.length < 1}
              >
                {intl.formatMessage({id:"FixLock.delete"})}
              </Button>,
            ]}
          />
          {/* 新增和修改对话框 */}
          {modalShow && (
            <AddOneRoom
              visible={modalShow}
              id={id}
              info={info}
              onCancel={() => {
                setModalShow(false);
                setId(0);
              }}
              done={() => actionRef.current?.reload()}
            />
          )}
        </>
      )}
      {show && <IdentityProvider setIsModalOpen={setShow} />}
    </>
  );
};

export default Index;
